package com.crime.crimemonitorclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import org.apache.http.HttpStatus;

import android.content.Context;
import android.location.Location;
import android.util.Log;

public class GetKodAktualnihoUtvaruAsyncTask extends RetainedAsyncTask<String>
{

	private Exception		mException;
	private final URL		mServiceURL;
	private final Location	mLocation;

	public GetKodAktualnihoUtvaruAsyncTask(URL serviceURL, Location location, AsyncTaskHandler<String> asyncTaskHandler)
	{
		super(asyncTaskHandler);
		
		if (serviceURL == null)
			throw new NullPointerException("serviceURL");

		if(location == null)
			throw new NullPointerException("location");
		
		this.mServiceURL = serviceURL;
		this.mLocation = location;
	}

	@Override
	protected String doInBackground(Void... args)
	{

		HttpURLConnection conn = null;
		BufferedReader isReader = null;

		try
		{
			URL serviceURL = new URL(
					String.format(Locale.ENGLISH, "%s/utvar?lat=%f&lon=%f",
							this.mServiceURL, this.mLocation.getLatitude(),
							this.mLocation.getLongitude()));

			conn = (HttpURLConnection) serviceURL.openConnection();

			if (conn.getResponseCode() == HttpStatus.SC_OK)
			{

				isReader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));

				String kodAktualnihoUtvaru = isReader.readLine();

				return kodAktualnihoUtvaru;

			}
			else
			{
				this.mException = new IOException(conn.getResponseMessage());
			}
		}
		catch (Exception e)
		{
			this.mException = e;
			this.cancel(false);
		}
		finally
		{
			try
			{
				if (conn != null)
					conn.disconnect();

				if (isReader != null)
				{
					isReader.close();

				}
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return null;
	}

	Exception getException()
	{
		return this.mException;
	}
}
